package qf.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import qf.api.RedisCacheApi;
import qf.exception.ExceptionDict;
import qf.exception.RedisException;

import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/cache")
@Api(description = "缓存的controller")
public class RedisController {

    @Autowired
    private RedisCacheApi redisServiceApi;

    /**
     * 保存字符串数据到redis中
     *
     * @param key
     * @param value
     * @param expire
     */
    @ApiOperation("添加字符串到缓存")
    @RequestMapping(value = "/save2cache",method = RequestMethod.GET)
    public boolean save2cache(@ApiParam(name = "key",required = true,defaultValue = "laowang") String key, @ApiParam(name = "value",required = true,defaultValue = "qianfengdiyijian")  String value, @ApiParam(required = true,defaultValue = "10000")  long expire) {
        //有效期是个数字,用户就可能会传递负数
        //有效期为负数的情况下我们应该如何处理,指的是你们如何处理,比如不管,报错,转成正数,认为不设置有效期等等都可以

        //我们无法控制用户,所以用户可能会出现参数不传递的情况
        checkKey(key);
        return redisServiceApi.set(key, value, expire);

    }

    @GetMapping("/get")
    public String get(String key){
        checkKey(key);
        return redisServiceApi.get(key);
    }


    /**
     * hash结构存储的值
     * 通过key获得redis中的对应的全部field，value
     * @param key
     * @return
     */

    @GetMapping("/hgetall/{key}")
    public Map<Object, Object> hgetAll(@PathVariable("key") String key) {
        checkKey(key);
        return redisServiceApi.hGetAll(key);
    }

    /**
     * set结构存储的值
     * 通过key获得redis中对应的set集合
     * @param key
     * @return
     */
    @RequestMapping("/members/{key}")
    public Set<String> members(@PathVariable String key) {
        checkKey(key);
        return redisServiceApi.setMembers(key);
    }

    @GetMapping("/hincr/{key}/{field}/{incr}")
    public Long hincr(@PathVariable String key,@PathVariable String field,@PathVariable Long incr){
        checkKey(key);
        checkKey(field);
        return redisServiceApi.hdecr(key,field,incr);
    }
    @GetMapping("/keys/{partten}")
    Set<String> keys(@PathVariable  String partten){
        checkKey(partten);
        return redisServiceApi.keys(partten);
    }

    @PostMapping("/hupdate/{key}")
    public void hupdate(@PathVariable String key,@RequestBody Map fieldValue){
        checkKey(key);
        redisServiceApi.hupdate(key,fieldValue);
    }



    private void checkKey(String key) {
        if (key == null || "".equalsIgnoreCase(key.trim())) {
            throw new RedisException(ExceptionDict.REDISKEYISNULL, "redis的key不能为空");
        }
    }

}
